package com.chunsoft.sort;

import static com.chunsoft.sort.SortUtils.*;

/**
 * Title: BubbleSort.java
 * Description: 冒泡排序
 * Create DateTime: 2023/10/24 21:52
 *
 * @author chunsoft
 */
public class BubbleSort {

    /**
     * 冒泡排序
     * @param arr 待排序数组
     */
    public static void bubbleSort(int[] arr) {

        if (arr == null || arr.length < 2) {
            return;
        }

        // i 比较的轮次，j 比较子范围
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1- i; j++) {
                if (arr[j] > arr[j+1]) {
                    swap(arr, j, j+1);
                }
            }
        }
    }

    /**
     * 验证函数
     * @param args 参数
     */
    public static void main(String[] args) {
        int testTime = 5;
        int maxSize = 100;
        int maxValue = 100;
        boolean succeed = true;
        for (int i = 0; i < testTime; i++) {
            int[] arr1 = generateRandomArray(maxSize, maxValue);
            printArray(arr1);
            int[] arr2 = copyArray(arr1);
            bubbleSort(arr1);
            comparator(arr2);
            if (!isEqual(arr1, arr2)) {
                succeed = false;
                break;
            }
        }
        System.out.println("验证结果：" + succeed);
    }
}
